use bevy::prelude::*;
use bevy::render::camera::Camera;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup)
        .add_systems(Update, (draw, close_on_esc))
        .run();
}

// 设置初始场景
fn setup(mut commands: Commands) {
    commands.spawn((Camera2d::default(), Transform::default(), GlobalTransform::default()));
}

// 处理鼠标输入并绘制线条
fn draw(
    mut commands: Commands,
    window: Query<&Window>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    camera_query: Query<(&Camera, &GlobalTransform)>,
) {
    if mouse_button_input.pressed(MouseButton::Left) {
        // 获取鼠标位置
        let window = window.single();
        if let Some(mouse_position) = window.cursor_position() {
            // 将鼠标位置转换为世界坐标
            let (camera, camera_transform) = camera_query.single();
            if let Ok(world_position) = camera.viewport_to_world_2d(camera_transform, mouse_position) {
                // 在鼠标位置生成一个点
                commands.spawn((
                    Sprite {
                        color: Color::srgb(1.0, 0.0, 0.0),
                        custom_size: Some(Vec2::new(2.0, 2.0)),
                        ..default()
                    },
                    Transform::from_xyz(world_position.x, world_position.y, 0.0),
                    GlobalTransform::default(),
                ));
            }
        }
    }
}

// 按ESC键关闭窗口
fn close_on_esc(
    mut app_exit_events: EventWriter<AppExit>,
    keyboard_input: Res<ButtonInput<KeyCode>>,
) {
    if keyboard_input.just_pressed(KeyCode::Escape) {
        app_exit_events.send(AppExit::Success);
    }
}
